
app.controller('applyDetailModalCtrl', ['$scope', 'httpLoad', '$rootScope','$modal','$state','$timeout','$stateParams','$sce',
     function($scope, httpLoad, $rootScope, $modal,$state, $timeout,$stateParams,$sce) {

       $rootScope.moduleTitle =$sce.trustAsHtml('应用服务 > <span>应用实例</span> > 详情');
       console.log($rootScope.userData);
       $scope.active1 = '';
	   ///
       (function(){
         var id = $stateParams.id;
       httpLoad.loadData({
           url:'/application/detail',
           method:'GET',
           data: {id: id},
           success:function(data){
               if(data.success&&data.data){
                   $scope.supplierDetail = data.data;
                   $scope.showDetail = $scope.isActive = true;

               }
           }
       });
       })();
       $scope.goBack = function(){
           $state.go('app.adhibition.apply');
       };
     }
 ]);
app.controller('applybasicModalCtrl', ['$rootScope', '$scope','$state','httpLoad','$stateParams',function($rootScope, $scope,$state,httpLoad,$stateParams) {

    $scope.param = {
        rows: 10
    };
       var id = $stateParams.id;
    $scope.initDetail = function(){
      httpLoad.loadData({
      url: '/pdb/detail',
      method: 'GET',
      data: {id: id},
      success: function (data) {
        if (data.success) {

           $scope.supplierDetail = data.data;
          $scope.nodeData = {
            targetName: $scope.supplierDetail.name,
            targetCategory: 'DB',
            relations: $scope.supplierDetail.resourceRelations
          };


        }
      }
    });
    }
//  $scope.initDetail()
}]);
app.controller('applyopenstackModalCtrl', ['$rootScope','$interval','webSocket','$modal','$timeout', '$scope','$state','httpLoad','LANGUAGE','$stateParams',
function($rootScope,$interval,webSocket, $modal,$timeout,$scope,$state,httpLoad,LANGUAGE,$stateParams) {
      var socket;
      var pageType;
    $scope.param = {
        rows: 10
    };
  //  websocket异步操作
    webSocket.onmessage({
    	message:function (data) {
    		if(($rootScope.currentUrl=="app.adhibition.applytiondetail")&&((data.operate=='application/scaleRc')||(data.operate=='/application/rolling')||(data.operate=='application/layoutDeploy')||(data.operate=='/application/rollback')||(data.operate=='/application/upgrade') ||(data.operate=='application/rolling'))){
		          if($scope.active1&&(pageType=="ReplicationController")){
		             $scope.search(1,'ReplicationController');
		          }

    		}
    	}
    });
    $scope.search = function (page,type) {
    	pageType = type
      $scope.param.page = page || $scope.param.page;
       $scope.param.params =  JSON.stringify([{"param": {"resourceType": type, "appId": $stateParams.id,id:''}, "sign": "EQ"}])
      httpLoad.loadData({
        url: '/app/statistic/list',
        method: 'POST',
        data: $scope.param,
        noParam: true,
        success: function (data) {
          if (data.success) {
            $scope.listData = data.data;
            $scope.total = data.data.length;
            if(!$scope.total){
              $scope.isImageData = true;
              } else {
                $scope.isImageData = false;
            }
          }
        }
      });
    };
    //详情
    $scope.goBack = function(){
           $scope.isActive = false;
           $timeout(function() {
               $scope.showDetail = false;
           }, 200);
           //终止监测
           $interval.cancel($scope.timeInterval);
           if(socket){
              socket.close();
           }

           $scope.showUp = false
       };

       ////滚动
             $scope.options = {
               	bucketDuration:0,
       				cpu:{
       					theme:'Cpu',
       					unit:'Millicores'
       				},
       				memorynode:{
       					theme:'Memory',
       					unit:'Gib'
       				},
       				memorypod:{
       					theme:'Memory',
       					unit:'MiB'
       				},
       				network:{
       					theme:'Network',
       					unit:'KiB/s'
       				},
             }
             $scope.paramObj = {
                resourceName:'',
                namespace:''
              };
              $scope.timeTypeData =[
                {
                  name :'Last hour',
                  value:0
                },{
                  name :'Last 4 hour',
                  value:1
                },{
                  name :'Last day',
                  value:2
                },{
                  name :'Last 3 day',
                  value:3
                },{
                  name :'Last week',
                  value:4
                }
              ]
           $scope.KubernetesData ={
            row:'',
             state:''
           }
              var bucketDuration =[120000,480000,2880000,8640000,20160000]
              var startTime =['-60mn','-240mn','-1440mn','-4320mn','-10080mn']
       //跳转详情页
       $scope.detail = function (row,type,$event) {
            	  $scope.KubernetesData.row = row;
         $scope.paramObj.resourceName = row.name;
          $scope.paramObj.namespace = row.namespace;
         var params = {"resourceType":type,"namespace":row.namespace,"resourceName":row.name,id:$stateParams.clusterId}
               switch (type) {
                case 'Master':
                    $scope.showDetail = 1;
                    break;

                case 'ReplicationController':
                    $scope.showDetail = 3;
                    break;
                case 'Service':
                    $scope.showDetail = 4;
                    break;
                case 'Pod':
                    $scope.showDetail = 5;
                    break;
                case 'HorizontalPodAutoscaler':
                    $scope.showDetail = 6;
                    break;

                  };
                  $event.stopPropagation();
                  $scope.isActive = true ;
                  httpLoad.loadData({
                       url:'/app/statistic/detail',
                       method:'POST',
                       data: params,
                       success:function(data){
                         if(data.success&&data.data){
                             $scope.supplierDetail = data.data;
                             if(type=='HorizontalPodAutoscaler'){
                               $scope.Status = $scope.supplierDetail.Status[0];
                                  $scope.Container = $scope.supplierDetail.Container;
                               $scope.Template = $scope.supplierDetail.Template;


                             }else if(type=='ReplicationController'){
                								 if($scope.supplierDetail.labels){
                										$scope.labels =  $scope.supplierDetail.labels.replace(/,/g,'/<br>')
                								}
                							 if($scope.supplierDetail.selectors){
                									$scope.selectors =  $scope.supplierDetail.selectors.replace(/,/g,'/<br>')
                							}
                             }else if(type=='Service'){
                               $scope.basicDetails = $scope.supplierDetail.basicDetails[0];
                               if($scope.basicDetails.selectors){
                                   $scope.selectors =  $scope.basicDetails.selectors.replace(/,/g,'/<br>')
                                }
                                if($scope.basicDetails.labels){
                                 $scope.labels =  $scope.basicDetails.labels.replace(/,/g,'/<br>')
                                }


                             }else if(type=='Pod'){
                                 $scope.Status = $scope.supplierDetail.Status[0];
                                    $scope.Container = $scope.supplierDetail.Container;
                                 $scope.Template = $scope.supplierDetail.Template;
                                 $scope.Volumes = $scope.supplierDetail.Volumes;
                                 for(var i=0;i<$scope.Container.length;i++){
                                   var item = $scope.Container[i]
                                     if(item.state=='running'){
                                         $scope.KubernetesData.state = true;
                                         $scope.KubernetesData.states = false;
                                       $scope.options.bucketContainer =item.containerName;
                                       $scope.options.bucketT =item.containerName
                                       $scope.options.bucketL =item.containerName
                                         $scope.getLog(item.state);
                                       $scope.getTeminal(row,type);
                                       $scope.chackIn(type,row)
                                       setTimeout(function(){
                                         if(!$('.kuberb option').eq(0).html()){
                                           $('.kubera option').eq(0).remove()
                                          $('.kuberb option').eq(0).remove()
                                          $('.kuberc option').eq(0).remove()
                                         }
                                       },100)
                                       return
                                     }else  if(item.state=='Completed'){
                                       $scope.options.bucketContainer =item.containerName;
                                       $scope.options.bucketT =item.containerName
                                       $scope.options.bucketL =item.containerName
                                         $scope.KubernetesData.state = true
                                         $scope.KubernetesData.states = true
                                           $scope.getLog(item.state);
                                       $scope.getTeminal(row,type);
                                       $scope.chackIn(type,row)
                                       setTimeout(function(){
                                         if(!$('.kuberb option').eq(0).html()){
                                           $('.kubera option').eq(0).remove()
                                          $('.kuberb option').eq(0).remove()
                                          $('.kuberc option').eq(0).remove()
                                         }
                                       },100)
                                       return
                                     }else {
                                       $scope.options.bucketContainer =$scope.Container[0].containerName;
                                       $scope.options.bucketT =$scope.Container[0].containerName
                                       $scope.options.bucketL =$scope.Container[0].containerName
                                         $scope.KubernetesData.state = false
                                        $scope.KubernetesData.states = true;
                                     }
                                 }
                                 setTimeout(function(){
                                   if(!$('.kuberb option').eq(0).html()){
                                     $('.kubera option').eq(0).remove()
                                    $('.kuberb option').eq(0).remove()
                                    $('.kuberc option').eq(0).remove()
                                   }
                                 },100)
                                 $scope.getLog(row.status);
                                 $scope.getTeminal(row,type);
                                 $scope.chackIn(type,row)
                           }else{
                             $scope.Source = $scope.supplierDetail.Source[0];
                               $scope.basicDetails = $scope.supplierDetail.basicDetails[0];
                               if($scope.basicDetails.labels){
                                     $scope.labels =  $scope.basicDetails.labels.replace(/,/g,'/<br>')
                                }


                           }

                         }
                       }
                   });

      //事
      if(type!='Master' && type != 'Node'){
          httpLoad.loadData({
             url: '/app/statistic/event',
             method: 'POST',
             data: params,
             success: function(data){
               if(data.success) {
                 $scope.isDataLoad = true;
                 $scope.listEventData = data.data;
                 $scope.totalEvent = data.data.length;
                 if(!$scope.totalEvent){
   								$scope.isImageDatad = true;
   								} else {
   									$scope.isImageDatad = false;
   							}
               }
             }
           });
      }

       };
       //终端
       $scope.getTeminal = function () {
         var row = $scope.KubernetesData.row;
         var notNormal = false;
           if(!$scope.KubernetesData.states){
               $scope.prompts = true
               socket = new WebSocket('ws://' + location.host +'/terminalService');
               socket.onopen = function()
                  {
                   socket.send(JSON.stringify({
                     'containerName':$scope.options.bucketT,
                     'url': row.proxyUrl,
                     'namespace':row.namespace,
                     'resourceName': row.name,
                     'command':'',
                     'flag':false
                   })
               )  };
               socket.onmessage = function (event) {
                 var obj = JSON.parse(event.data);
                 $scope.socketFlag=obj.flag;
               };
               setTimeout(function(){
                 $('#kebernet').terminal(function(command, term) {
                   //开始执行
                   // Web Socket 已连接上，使用 send() 方法发送数据
                   if(command){
                     if(!notNormal){
 												socket.send(JSON.stringify({
 													'command':command,
 													'flag':$scope.socketFlag,
 												}))
 											}else{
 												socket.send(JSON.stringify({
 													'containerName':$scope.options.bucketT,
 													'url': row.proxyUrl,
 													'namespace':row.namespace,
 													'resourceName': row.name,
 													'notFalg':'notNormal',
 													'command':command,
 													'flag':false
 												})
 										)
 											}

                   term.disable()
                   }
                   socket.onmessage = function (event) {
                     var obj = JSON.parse(event.data);
                     if(obj.data){
                       $scope.socketFlag=obj.flag;
   												if(obj.notFalg=='notNormal'){
   													notNormal = true;
   												}else{
   													notNormal = false;
   												}
   												term.echo(String(obj.data));
   												term.enable()
   											}else{
                       term.enable()
                     }
                   };
         }, {
                 greetings: "",//
             height:500,
             width:'100%',
             'font-size':'15px',
             prompt: '# ',
                 onBlur: function() {
                     // prevent loosing focus
                     return false;
                 }
               });
         },100)
           }else{
             $scope.prompts = false
           }
       }
       //日志
       $scope.getLog = function (status) {
         var row = $scope.KubernetesData.row
         var params = {
           "resourceType":'Pod',
           "namespace":row.namespace,
           "resourceName":row.name,
           'containerName':$scope.options.bucketL,
           'status':status,
           id:$stateParams.clusterId
         }
         httpLoad.loadData({
           url: '/app/statistic/log',
           method: 'GET',
           data: params,
             success: function(data){
               if(data.data==null){
                 $scope.logPod = data.data;
               }else{
                 $scope.logPod = data.data.replace(/\n/g,'<br>');
               }
             }
           });
       }

       $scope.showUps = function () {
        $scope.showUp = true
      }
       $scope.chackIn = function(type,row){
         	if(type!='Pod'){return}
          if(type == 'Pod'&&!$scope.KubernetesData.state){
						$scope.prompt = false;return
					}else{
						$scope.prompt = true;
					}
    	   $scope.monitored();
    	    $scope.timeInterval = $interval(function () {
    	        $scope.monitored ();
    	      }, 120*1000);
       }
       //监控
       $scope.monitored = function () {
         var paramObj = {
             type:'pod',
             startTime:startTime[$scope.options.bucketDuration],
             bucketDuration:bucketDuration[$scope.options.bucketDuration],
             resourceName:$scope.paramObj.resourceName,
             namespace:$scope.paramObj.namespace,
                id:$stateParams.clusterId
         };
          httpLoad.loadData({
              url: '/openshift/monitor/kubernetes/monitor',
              method: 'GET',
              data:paramObj,
            //  noParam:true,
              success: function(data){
                if(data.success) {
                  $scope.time = data.data.CPU.keys[data.data.CPU.keys.length-1]
                  $scope.performance = data.data;

               }else if($scope.timeInterval){
                   $interval.cancel($scope.timeInterval);
                   $scope.timeInterval = '';
               }
              }
            });

       }

    $scope.goAction = function (flag, row,type,$event) {
      switch (flag / 1) {
        //yaml

        case 2:
        //删除
        var modalInstance = $modal.open({
          templateUrl : '/statics/tpl/adhibition/apply/remove.html',
          controller : 'removeApplyTypeModalCtrl',
          	backdrop: 'static',
          resolve : {
        	  row : function(){
                  return row;
                },
               type:function(){
                    return type;
                  },

          }
        });
        modalInstance.result.then(function(){
          $scope.search(1,type);
          $scope.isCheck = false;
        },function(){});

          break;
        case 3:
          //详情
          $scope.detail(row,type,$event)
          break;
        case 4:
            //资源
        	var param = {};
            param.params=angular.toJson([{"param":{}}])
            param.resourceType = "ReplicationController";
            param.resourceName = row.name;
            param.namespace = row.namespace;
            param.appId = $stateParams.id;
            httpLoad.loadData({
                url:'/application/getPodResource',
                method:'POST',
                data: param,
                noParam: true,
                success:function(data){
                    "use strict";
                    if(data.success){
                        var modalInstance = $modal.open({
                            templateUrl : '/statics/tpl/adhibition/apply/resource.html',
                            controller : 'applyResourceModalCtrl',// 初始化模态范围
                            backdrop: 'static',
                            resolve : {
                                row : function(){
                                    return row;
                                },
                                type:function(){
                                    return type;
                                },
                            }
                        });
                        modalInstance.result.then(function(){
                            $scope.search(1,type);
                        },function(){});
                    }else{

                    }
                }
            })
          break;
        case 5:
              //pod
        	var param = {};
            param.params=angular.toJson([{"param":{}}])
            param.resourceType = "ReplicationController";
            param.resourceName = row.name;
            param.namespace = row.namespace;
            param.appId = $stateParams.id;
            httpLoad.loadData({
                url:'/application/getHPA',
                method:'POST',
                data: param,
                noParam: true,
                success:function(data){
                    "use strict";
                    if(data.success){
                        var modalInstance = $modal.open({
                            templateUrl : '/statics/tpl/adhibition/apply/pod.html',
                            controller : 'applyPodModalCtrl',// 初始化模态范围
                            backdrop: 'static',
                            resolve : {
                                row : function(){
                                    return row;
                                },
                                type:function(){
                                    return type;
                                },

                            }
                        });
                        modalInstance.result.then(function(){
                            $scope.search(1,type);
                        },function(){});
                    }else{
                        
                    }
                }
            })
          break;
        case 6:
                //版本回滚
        		var msg = "6"
                var modalInstance = $modal.open({
                    templateUrl : '/statics/tpl/adhibition/apply/remove.html',
                    controller : 'applyRollbackModalCtrl',// 初始化模态范围
                    backdrop: 'static',
                    resolve : {
                        row : function(){
                            return row;
                        },
                        msg:function(){
                            return msg;
                          },

                    }
                });
                modalInstance.result.then(function(){
                      $scope.search(1,type);
                      $scope.active1=true; 
                },function(){});

          break;
          case 7:
              //滚动升级
              var modalInstance = $modal.open({
                  templateUrl : '/statics/tpl/adhibition/apply/updeta.html',
                  controller : 'applyUpgradeModalCtrl',// 初始化模态范围
                	backdrop: 'static',
                  resolve : {
                      row : function(){
                          return row;
                      },
                      msg:function(){
                          return 7;
                        },
              

                  }
              });
              modalInstance.result.then(function(){
                    $scope.search(1,type);
                    $scope.active1=true;
              },function(){});

            break;
          case 8:
                    //修改实例
        	   var param = {};
               param.params=angular.toJson([{"param":{}}])
               param.resourceType = "ReplicationController";
               param.resourceName = row.name;
               param.namespace = row.namespace;
               param.appId = $stateParams.id;
                    httpLoad.loadData({
                        url:'/application/getHPA',
                        method:'POST',
                        data: param,
                        noParam: true,
                        success:function(data){
                        	if (data.success) {
                        		if(data.data.cpuTargetUtilization){
                                    var modalInstance = $modal.open({
                                      templateUrl: '/statics/tpl/template/delModal.html',
                                      controller: 'delModalCtrl',
                                      backdrop: 'static',
                                      resolve: {
                                        tip: function () {
                                          return '当前部署已设置弹性伸缩，不支持手动修改实例数，若需要手动修改实例数，请删除该部署的弹性伸缩';
                                        },
                                        btnList: function () {
                                          return [{name: '取消', type: 'btn-cancel'}];
                                        }
                                      }
                                    });
                                  }else{
                                    var modalInstance = $modal.open({
                                        templateUrl : '/statics/tpl/adhibition/apply/chagePod.html',
                                        controller : 'applychagePodModalCtrl',// 初始化模态范围
                                        backdrop: 'static',
                                        size:'lg',
                                        resolve : {
                                          row : function(){
                                              return row;
                                          },
                                          type:function(){
                                            return type;
                                          },

                                        }
                                    });
                                    modalInstance.result.then(function(){
                                          $scope.search(1,type);
                                    },function(){});
                                  }

                                } 
                        	}
                          
                      })


          break;
          case 9:
          //部署历史
          $event.stopPropagation();
                var param = {
                        page:1,
                        rows: 10,
                        params:angular.toJson([{"param":{"resourceName":row.name},"sign":"LK"}])
                    };
                    httpLoad.loadData({
                      url: '/deployHistory/list',
                        method:'POST',
                        data: param,
                        noParam:true,
                        success:function(data){
                          $scope.showDetail = 2;
                          $scope.isActive = true ;
                            if(data.success&&data.data){
                                $scope.userList = data.data.rows;
                                $scope.totalCount = data.data.total;
                                if(data.data.rows==[]){
                                    $scope.pop("返回数据为空");
                                }
                                if (data.data.rows.length == 0) {
                                  $scope.isImageDatad = true;
                                  return;
                                } else $scope.isImageDatad = false;

                            }

                        }
                    });


          break;
          case 10:
              //重建服务
        	  var msg ="10"
        	  var modalInstance = $modal.open({
                  templateUrl : '/statics/tpl/adhibition/apply/remove.html',
                  controller : 'applyRollbackModalCtrl',// 初始化模态范围
                  backdrop: 'static',
                  resolve : {
                      row : function(){
                          return row;
                      },
                      msg:function(){
                          return msg;
                        },

                  }
              });
              modalInstance.result.then(function(){
                    $scope.search(1,type);
              },function(){});
          break;
          case 11:
              //重建服务
        	  var modalInstance = $modal.open({
                  templateUrl : '/statics/tpl/adhibition/apply/updeta.html',
                  controller : 'applyUpgradeModalCtrl',// 初始化模态范围
                	backdrop: 'static',
                  resolve : {
                      row : function(){
                          return row;
                      },
                      msg:function(){
                          return 11;
                        },

                  }
              });
              modalInstance.result.then(function(){
                    $scope.search(1,type);
                    $scope.active1=true;
              },function(){});
          break;
      }
    };


}]);
//Resource
 angular.module('app').controller('applyResourceModalCtrl',['$scope','$stateParams','$modalInstance','LANGUAGE','httpLoad','row','type',
     function($scope,$stateParams,$modalInstance,LANGUAGE,httpLoad,row,type){ //依赖于modalInstance
       var editObj = ['cpuRequest','cpuLimit','memoryRequest','memoryLimit'];
         $scope.addData = {};
         $scope.$parent.cpuRequest = $scope.$parent.cpuLimit ="m"
         $scope.$parent.memoryRequest = $scope.$parent.memoryLimit ="M"
         $scope.appResource = [
           {
             name:'MiB',
             value:'Mi'
           },
           {
             name:'GIB',
             value:'Gi'
           },
           {
             name:'MB',
             value:'M'
           },
           {
             name:'GB',
             value:'G'
           }
         ]

   			$scope.unit = {
   					'K':1,
   					'M':1000,
   					'G':1000*1000,
   					'T':1000*1000*1000,
            'P':1000*1000*1000*1000,
            'E':1000*1000*1000*1000*1000,
            'Ki':1,
            'Mi':1024,
            'Gi':1024*1024,
            'Ti':1024*1024*1024,
            'Pi':1024*1024*1024*1024,
            'Ei':1024*1024*1024*1024*1024
   			}

        //获取资源
       var param = {};
       param.params=angular.toJson([{"param":{}}])
       param.resourceType = "ReplicationController";
       param.resourceName = row.name;
       param.namespace = row.namespace;
       param.appId = $stateParams.id;
       httpLoad.loadData({
           url:'/application/getPodResource',
           method:'POST',
           data: param,
           noParam: true,
           success:function(data){
               if(data.success){
            	   if(data.cpuLimit.match(/\d+/gi)){
            		   $scope.addData.cpuLimit = data.cpuLimit.match(/\d+/gi).join();
            	   }
            	   if(data.cpuRequest.match(/\d+/gi)){
            		   $scope.addData.cpuRequest = data.cpuRequest.match(/\d+/gi).join();
            	   }
            	   if(data.memoryRequest.match(/\d+/gi)){
            		   $scope.addData.memoryRequest = data.memoryRequest.match(/\d+/gi).join();
            	   }
            	   if(data.memoryLimit.match(/\d+/gi)){
            		   $scope.addData.memoryLimit = data.memoryLimit.match(/\d+/gi).join();
            	   }
          if(data.cpuLimit.match(/[a-zA-Z]+/gi)){
              $scope.$parent.cpuLimit = data.cpuLimit.match(/[a-zA-Z]+/gi).join();
          }else{
            $scope.$parent.cpuLimit=''
          }
          if(data.cpuRequest.match(/[a-zA-Z]+/gi)){
              $scope.$parent.cpuRequest = data.cpuRequest.match(/[a-zA-Z]+/gi).join();
          }else{
              $scope.$parent.cpuRequest = ''
          }
          		if(data.memoryRequest.match(/[a-zA-Z]+/gi)){
          		  var Request= data.memoryRequest.match(/[a-zA-Z]+/gi).join();
	          	    if(Request!='M'&&Request!='G'&&Request!='Mi'&&Request!='Gi'){
			            var a =  {
			               name:Request,
			               value:Request
			             }
			            $scope.appResource.push(a)
			            $scope.$parent.memoryRequest = Request
			          }else{
			            $scope.$parent.memoryRequest = Request
			          }
	          		}
			      if(data.memoryLimit.match(/[a-zA-Z]+/gi)){
			    	  var Limit = data.memoryLimit.match(/[a-zA-Z]+/gi).join();

			          if(Limit!='M'&&Limit!='G'&&Limit!='Mi'&&Limit!='Gi'){
			            var b =  {
			               name:Limit,
			               value:Limit
			             }
			            $scope.appResource.push(b)
			              $scope.$parent.memoryLimit = Limit
			          }else{
			              $scope.$parent.memoryLimit = Limit
			          }
			      }

               }
           }
       });


        $scope.ok = function () {

        var cpuLimit = $scope.addData.cpuLimit + $scope.$parent.cpuLimit;
        var cpuRequest = $scope.addData.cpuRequest +   $scope.$parent.cpuRequest;
        var memoryRequest = $scope.addData.memoryRequest + $scope.$parent.memoryRequest;
        var memoryLimit = $scope.addData.memoryLimit + $scope.$parent.memoryLimit;

        	// var cpuLimit = $scope.addData.cpuLimit*$scope.unit[$scope.$parent.cpuLimit] + "m";
        	// var cpuRequest = $scope.addData.cpuRequest*$scope.unit[$scope.$parent.cpuRequest] + "m";
        	// var memoryLimit = $scope.addData.memoryLimit*$scope.unit[$scope.$parent.memoryLimit] + "M";
        	// var memoryRequest = $scope.addData.memoryRequest*$scope.unit[$scope.$parent.memoryRequest] + "M";
//CPU
            if($scope.$parent.cpuLimit==""&&$scope.$parent.cpuRequest!=""){
              if(($scope.addData.cpuLimit*1000) < ($scope.addData.cpuRequest)){
                 $scope.pop("CPU的limit必须大于或等于request",'error');
                return;
              }
            }else  if($scope.$parent.cpuLimit!=""&&$scope.$parent.cpuRequest==""){
                if(($scope.addData.cpuLimit) < ($scope.addData.cpuRequest*1000)){
                   $scope.pop("CPU的limit必须大于或等于request",'error');
                  return;
                }
              }else {
                if(($scope.addData.cpuLimit) < ($scope.addData.cpuRequest)){
                   $scope.pop("CPU的limit必须大于或等于request",'error');
                  return;
                }
              }
    //Memory
            if($scope.$parent.memoryLimit.length==1&&$scope.$parent.memoryRequest.length==2){
              if(($scope.addData.memoryLimit*$scope.unit[$scope.$parent.memoryLimit]) < ($scope.addData.memoryRequest*$scope.unit[$scope.$parent.memoryRequest]/1024*1000)){
                 $scope.pop("Memory的limit必须大于或等于request",'error');
              return
              }
            }else  if($scope.$parent.memoryLimit.length==2&&$scope.$parent.memoryRequest.length==1){
              if(($scope.addData.memoryLimit*$scope.unit[$scope.$parent.memoryLimit]/1024*1000)< ($scope.addData.memoryRequest*$scope.unit[$scope.$parent.memoryRequest])){
                 $scope.pop("Memory的limit必须大于或等于request",'error');
              return
              }
            }else {
              if(($scope.addData.memoryLimit*$scope.unit[$scope.$parent.memoryLimit]) < ($scope.addData.memoryRequest*$scope.unit[$scope.$parent.memoryRequest])){
                 $scope.pop("Memory的limit必须大于或等于request",'error');
              return
              }
            }

            var limits = {};
           limits.cpu=cpuLimit;
           limits.memory=memoryLimit;
            var requests = {};
            if($scope.addData.cpuRequest){
            	requests.cpu=cpuRequest;
            }
            if($scope.addData.memoryRequest){
            	requests.memory=memoryRequest
            }

              if($scope.addData.memoryLimit*$scope.unit[$scope.$parent.memoryLimit]<4000){
                $scope.pop("limit必须大于4M",'error');
                  return
              }else {
                if($scope.addData.memoryLimit.toString().split(".")[1]){
                  if($scope.addData.memoryLimit.toString().split(".")[1].length>2){
                    $scope.pop("小数点不能多于2位",'error');
                    return
                  }
              }else {
              }
              }
	        var param = {
	        	params:angular.toJson({"rcName":row.name,
	        		"namespace":row.namespace,
	        		"limits":limits,
	        		"requests":requests,
	        		appId:$stateParams.id
	        		})
	        };
             httpLoad.loadData({
                 url:'/application/editRcResource',
                 method:'POST',
                 data: param,
                 noParam: true,
                 success:function(data){
                     if(data.success){
                        	$scope.pop(data.message);
                         $modalInstance.close();
                     }
                 }
             });
         }

         $scope.cancel = function(){
          $modalInstance.dismiss('cancel');
         };
     }]);
     //删除ctrl
     angular.module('app').controller('removeApplyTypeModalCtrl',['$scope','$stateParams','$modalInstance','httpLoad','LANGUAGE'
                                                                  ,'row','type',
       function($scope,$stateParams,$modalInstance,httpLoad,LANGUAGE,row,type){ //依赖于modalInstance
         if(type=='Pod'){
             $scope.messageApply = ' 是否确认删除该条实例？';
          } else if(type=='Service'){
            $scope.messageApply = ' 服务删除将会导致应用异常，确认删除？';
          } else if(type=='ReplicationController'){
            $scope.messageApply = ' 删除部署则相关的实例也会删除，确认删除？';
          } else if(type=='HorizontalPodAutoscaler'){
            $scope.messageApply = ' 弹性伸缩将被删除，确认删除？';
          } else {
            $scope.messageApply = '部署和运行实例都将被彻底删除，确认删除？';
          }


         var param = {};
         param.params=angular.toJson([{"param":{}}])
         param.resourceType = type;
         param.resourceName = row.name;
         param.namespace = row.namespace;
         param.appId = $stateParams.id;
         $scope.ok = function(){
              $scope.isCheck = true;
           httpLoad.loadData({
             url:'/application/deleteResource',
             method:'POST',
             data: param,
             noParam: true,
             success:function(data){
               if(data.success){
              	$scope.pop(data.message);
                 $modalInstance.close();
               }
             }
           });
         };
         $scope.cancel = function(){
          $modalInstance.dismiss('cancel');
         }
       }]);
//pod
 angular.module('app').controller('applyPodModalCtrl',['$scope','$stateParams','$modalInstance','LANGUAGE','httpLoad','row','type',
     function($scope,$stateParams,$modalInstance,LANGUAGE,httpLoad,row,type){ //依赖于modalInstance
       var editObj = ['requestValue','minReplicas','maxReplicas'];
         $scope.addData = {};

         //获取资源
         var param = {};
         param.params=angular.toJson([{"param":{}}])
         param.resourceType = "ReplicationController";
         param.resourceName = row.name;
         param.namespace = row.namespace;
         param.appId = $stateParams.id;
         httpLoad.loadData({
             url:'/application/getPodResource',
             method:'POST',
             data: param,
             noParam: true,
             success:function(data){
                 if(data.success){
                   if(!data.data.cpuRequest){
                            $scope.podmessage = '该资源没设置cpu的请求值，请先更改资源限制！'
                          $scope.chackIn = true;
                   }else {
                       $scope.chackIn = false
                   }
                 }
             }
         });
         httpLoad.loadData({
             url:'/application/getHPA',
             method:'POST',
             data: param,
             noParam: true,
             success:function(data){
                 if(data.success){
                   $scope.addData.minReplicas = data.minReplicas;
                   $scope.addData.maxReplicas = data.maxReplicas;
                   //选择CPU核数和内存大小
                   if(!data.cpuTargetUtilization){
                	   $scope.slider = {
                               value:0,
                              options: {
                                  floor: 0,
                                  ceil: 100
                                }

                        };
                   }else{
                	   $scope.slider = {
                               value:data.cpuTargetUtilization,
                              options: {
                                  floor: 0,
                                  ceil: 100
                                }

                        };
                   }
                 }else{
                	 $modalInstance.close();
                 }
             }
         });

        $scope.ok = function () {
             var param = {};
             editObj.forEach(function(attr){

				 if(attr=="requestValue"){
					 param[attr] = $scope.addData[attr]+'m';
				 }else{
					 param[attr] = $scope.addData[attr];
				 }

				});
        if(param.maxReplicas<=param.minReplicas){
          	$scope.pop('最小实例数必须小于最大实例数','error');
            return
        }
            param.params=angular.toJson([{"param":{}}]);
            param.appId = $stateParams.id;
            param.resourceName = row.name;
            param.namespace = row.namespace;
            param.cpuTargetUtilization =  $scope.slider.value;
             httpLoad.loadData({
                 url:'/application/autoScale',
                 method:'POST',
                 data: param,
                 noParam: true,
                 success:function(data){
                     if(data.success){
                        	$scope.pop(data.message);
                         $modalInstance.close();
                     }
                 }
             });
         }

         $scope.cancel = function(){
            $modalInstance.dismiss('cancel');
         };
     }]);
     //Rollback
      angular.module('app').controller('applyRollbackModalCtrl',['$scope','$stateParams','$modalInstance','LANGUAGE','httpLoad','row','msg',
          function($scope,$stateParams,$modalInstance,LANGUAGE,httpLoad,row,msg){ //依赖于modalInstance
          if(msg=='6'){
        	  $scope.messageApply = '是否回滚上个版本？';
        	  $scope.Url='/application/rollback'
          } else if(msg == '10'){
        	  $scope.messageApply = '是否重建该部署的所有服务？重建过程中请不要中断操作，可能会造成服务没有办法恢复！';
        	  $scope.Url='/application/rebuildServices'
          }
    	 
            var params = {
                    simple: true
            }

             $scope.ok = function () {
            	 
               $scope.param={}
               $scope.param.appId=$stateParams.id;
               $scope.param.params=angular.toJson([{"param":{}}])
               $scope.param.softwareId=$scope.imageId;
               $scope.param.resourceName=row.name;
               $scope.param.namespace=row.namespace;
               
                  httpLoad.loadData({
                      url:$scope.Url,
                      method:'post',
                      data: $scope.param,
                      noParam:true,
                      success:function(data){
     					 if (data.success) {
     						$scope.pop(data.message);
     						$modalInstance.close();
     					 }

                      }
                  });
              }

              $scope.cancel = function(){
              $modalInstance.dismiss('cancel');
              };
          }]);

//upgrade
 angular.module('app').controller('applyUpgradeModalCtrl',['$scope','$stateParams','$modalInstance','LANGUAGE','httpLoad','row','msg',
     function($scope,$stateParams,$modalInstance,LANGUAGE,httpLoad,row,msg){ //依赖于modalInstance
       $scope.scriptItem = {}
       var url = ""
       if(msg==7){
    	   $scope.modalName ="滚动升级";
    	   url = '/application/rolling'
       }else if(msg==11){
    	   $scope.modalName ="全量升级";
    	   url = "/application/upgrade"
       }
       var params = {
               simple: true
       }
         httpLoad.loadData({
                url: '/software/list',
                method: 'POST',
                data: params,
                noParam: true,
                success: function (data) {
                    if (data.success) {
                        $scope.dataType = data.data.rows;
                    }
                }
            });
        $scope.ok = function () {	
          $scope.param={}
          $scope.param.params=angular.toJson([{"param":{}}])
          $scope.param.appId=$stateParams.id;
          $scope.param.resourceName=row.name;
          $scope.param.namespace=row.namespace;
		  if(!$scope.scriptItem.selected){
				$scope.pop("镜像名称不能为空");
				return
			  }
		  $scope.param.softwareId=$scope.scriptItem.selected.id;
             httpLoad.loadData({
                 url:url,
                 method:'post',
                 data: $scope.param,
                 noParam:true,
                 success:function(data){
                   if(data.success){
                      $scope.pop(data.message);
            		  $modalInstance.close();
                   }
                 }
             });
         }

         $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
         };
     }]);

//applychagePodModalCtrl
angular.module('app').controller('applychagePodModalCtrl',['$scope','$stateParams','$modalInstance','LANGUAGE','httpLoad','row','type',
    function($scope,$stateParams,$modalInstance,LANGUAGE,httpLoad,row,type){ //依赖于modalInstance


  //选择CPU核数和内存大小

      httpLoad.loadData({
          url:'/application/getReplicas',
          method:'POST',
          data: {params:angular.toJson([{"param":{}}]),namespace:row.namespace,resourceName:row.name,resourceType:type,appId:$stateParams.id},
          noParam: true,
          success:function(data){
              if(data.success){

                $scope.slider = {
                       value:  data.data,
                       options: {
                           floor: 0,
                           ceil: 100
                         }

                };
              }
              else {
                $scope.slider = {
                       value:  0,
                       options: {
                           floor: 0,
                           ceil: 100
                         }

                };
              }
          }
      });



       $scope.ok = function () {
            var param = {};
            param.name = row.name;
            param.namespace = row.namespace;
           param.appId =$stateParams.id;
           param.count =  $scope.slider.value;
            httpLoad.loadData({
                url:'/application/scaleRc',
                method:'POST',
                data: param,
              //  noParam: true,
                success:function(data){
                    if(data.success){
                       	$scope.pop(data.message);
                        $modalInstance.close();
                    }else{
        								$modalInstance.close();
        						}
                }
            });
        }

        $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
        };
    }]);
app.controller('applyhistoryModalCtrl', ['$rootScope', '$scope','$state','httpLoad','$stateParams',function($rootScope, $scope,$state,httpLoad,$stateParams) {
	$rootScope.link = '/statics/css/alarm.css';//引入页面样式
  $scope.param = {
  		page:1,
 	        rows: 10,
 	        params:angular.toJson([{"param":{"object":"software"},"sign":"LK"}])
 	    };
    $scope.getData = function (page) {
      var id = $stateParams.id;
      httpLoad.loadData({
        url: '/log/list',
          method:'POST',
          data: $scope.param,
          noParam:true,
          success:function(data){
              if(data.success&&data.data){
                  $scope.userList = data.data.rows;
                  $scope.totalCount = data.data.total;
                  if(data.data.rows==[]){
                      $scope.pop("返回数据为空");
                  }
                  if (data.data.rows.length == 0) {
                    $scope.isImageData = true;
                    return;
                  } else $scope.isImageData = false;
              }

          }
      });
  }

}]);

//部署文件
app.controller('applyArrangeModalCtrl', ['$rootScope', '$scope','$state','httpLoad','$stateParams',function($rootScope, $scope,$state,httpLoad,$stateParams) {
  $scope.detail = function(id){
    $state.go('app.adhibition.modeldetail', {id: id})

  }
    $scope.param = {
        page:1,
        rows: 10
    };
    $scope.getData = function (page) {
   	 var port = $stateParams.port;
     $scope.param.page = page || $scope.param.page;
     $scope.param.params=angular.toJson([{"param":{},"sign":"EQ"}])
     $scope.param.appId=$stateParams.id
     httpLoad.loadData({
         url: '/layout/listByAppId',
       method: 'POST',
       data: $scope.param,
       noParam: true,
       success: function (data) {
         if (data.success) {
           $scope.countData = data.data.rows;
           $scope.totalCount = data.data.total;
         }
       }
     });
   };
}]);

app.controller('applyStrategyModalCtrl', ['$rootScope', '$scope','$state','httpLoad','$stateParams',function($rootScope, $scope,$state,httpLoad,$stateParams) {
 $scope.detail = function(id){
   $state.go('app.sortware.dockerimagedetail', {id: id})

 }
   $scope.param = {
       page:1,
       rows: 10
   };
   $scope.getData = function (page) {
   	 var port = $stateParams.port;
     $scope.param.page = page || $scope.param.page;
     $scope.param.params=angular.toJson([{"param":{"application_id":$stateParams.id},"sign":"EQ"}])

     httpLoad.loadData({
       url: '/applicationSoftware/list',
       method: 'POST',
       data: $scope.param,
       noParam: true,
       success: function (data) {
         if (data.success) {
           $scope.countData = data.data.rows;
           $scope.totalCount = data.data.total;
         }
       }
     });
   };
}]);
